package com.qk.management.web.filter;

import com.qk.management.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Objects;

/**
 * @author 16778
 * @date 2025/10/11 10:58
 * @description
 */
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    public static final String LOGIN_PATH = "/login";
    public static final String TOKEN_NAME = "token";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String path = request.getRequestURI();
        log.info("请求路径:{}",path);
        if(path.contains(LOGIN_PATH)){
            filterChain.doFilter(request,response);
            return;
        }
        String token = request.getHeader(TOKEN_NAME);
        if(Objects.equals(token,null)){
            response.setStatus(401);
            return;
        }
        try {
            Claims claims = JwtUtils.parseToken(token);
            filterChain.doFilter(request,response);
        } catch (Exception e) {
            response.setStatus(401);
        }
    }
}
